package com.teng.mylibrary.base

import android.app.AlarmManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.ActivityInfo
import android.os.Build
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.text.TextUtils
import android.util.Log
import android.view.*
import android.view.inputmethod.InputMethodManager
import android.widget.HorizontalScrollView
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.alibaba.android.arouter.launcher.ARouter
import com.shehuan.library.StatusView
import com.tbruyelle.rxpermissions3.RxPermissions
import com.teng.mylibrary.R
import com.teng.mylibrary.Constants
import com.teng.mylibrary.widget.ProgressDialog
import com.teng.mylibrary.widget.ProTextDialog
import android.view.MotionEvent
import com.teng.mylibrary.util.ToastHelper
import com.teng.mylibrary.util.statusbar.StatusBarUtil


/**
 * Description:  基类Activity
 * Author:       liuteng
 * CreateDate:   2021/11/2 14:41
 * UpdateRemark: 更新说明
 */
abstract class BaseActivity<V : ViewDataBinding, VM : BaseViewModel> : AppCompatActivity() {

    protected lateinit var binding: V
    protected lateinit var viewModel: VM
    protected var mLastActionTime: Long = 0 //上一次操作时间
    private var filter: IntentFilter? = null
    private var receiver: BroadcastReceiver? = null
    protected val rxPermissions by lazy { RxPermissions(this) }
    protected val mProgressDialog by lazy {
        ProgressDialog(this, R.style.loading_dialog_style)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // TODO: 2022/10/9 手机和平板设置，全局搜索一下手机或者平板
        //设置竖屏
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        //设置横屏
//        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
        //显示返回按钮
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        //软键盘控制
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN or WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
        //注入阿里路由
        ARouter.getInstance().inject(this)
        initViewDataBinding(savedInstanceState)
        registeredUiChangeLiveDataCallBack()
        if (isTranslucentSutatus()) {
            initStatusBar()
        }
        //注册扫码广播
        if (isUseScanCode()) {
            initScanBroadcast()
        }
        initView()
        initData()
    }

    fun initStatusView(view: StatusView) {
//        view.setLoadingView(@LayoutRes int layoutId);
//        view.setErrorView(@LayoutRes int layoutId);
        view.setEmptyView(R.layout.empty_view)
        //默认显示空数据布局
//        view.showEmptyView()
        viewModel.uc.showEmptyView.observe(this, {
            view.showEmptyView()
        })
        viewModel.uc.showDataView.observe(this, {
            view.showContentView()
        })
    }

    private fun initViewDataBinding(savedInstanceState: Bundle?) {
        //DataBindingUtil类需要在project的build中配置 dataBinding {enabled true }, 同步后会自动关联android.databinding包
        binding = DataBindingUtil.setContentView(this, initContentView(savedInstanceState))
        //获取自定义的viewModel
        viewModel = initViewModel()
        //支持LiveData绑定xml，数据改变，UI自动会更新
        binding.lifecycleOwner = this
        //让ViewModel拥有View的生命周期感应
        lifecycle.addObserver(viewModel)

    }

    private fun registeredUiChangeLiveDataCallBack() {
        //显示加载动画弹框
        viewModel.uc.showDialogEvent.observe(this, {
            mProgressDialog.show()
        })
        //隐藏加载动画弹框
        viewModel.uc.dismissDialogEvent.observe(this, {
            mProgressDialog.dismiss()
        })
        //显示Toast弹框
        viewModel.uc.showToastOkEvent.observe(this, {
            ToastHelper.showOk(this, it)
        })
        //显示Toast弹框
        viewModel.uc.showToastOtherEvent.observe(this, {
            ToastHelper.showOther(this, it)
        })
        //显示单项内容提示
        viewModel.uc.showProTextEvent.observe(this, {
            showProMsg(it)
        })
        //结束当前页
        viewModel.uc.finishPageEvent.observe(this, {
            finish()
        })
        //隐藏键盘
        viewModel.uc.hideKeyboard.observe(this, {
            hideInputKeyboard(it)
        })
    }


    abstract fun initContentView(savedInstanceState: Bundle?): Int

    protected abstract fun initViewModel(): VM

    private fun initStatusBar() {
        //沉浸式代码配置
        //当FitsSystemWindows设置 true 时，会在屏幕最上方预留出状态栏高度的 padding
        StatusBarUtil.setRootViewFitsSystemWindows(this, false)
        //设置状态栏透明
        StatusBarUtil.setTranslucentStatus(this)
        //所以如果你是这种情况,请使用以下代码, 设置状态使用深色文字图标风格, 否则你可以选择性注释掉这个if内容
        if (!StatusBarUtil.setStatusBarDarkTheme(this, true)) {
            //如果不支持设置深色风格 为了兼容总不能让状态栏白白的看不清, 于是设置一个状态栏颜色为半透明,
            //这样半透明+白=灰, 状态栏的文字能看得清
            StatusBarUtil.setStatusBarColor(this, 0x55000000)
        }
    }

    private fun initScanBroadcast() {
        filter = IntentFilter()
        filter?.addAction(Constants.ACTION_IDATA)
        filter?.addAction(Constants.ACTION_SUNMI)
        filter?.addAction(Constants.ACTION_FULIYE)
        filter?.addAction(Constants.ACTION_NEW_LAND)
        filter?.addAction(Constants.ACTION_YUNDA)
        receiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                var result: String? = null
                when {
                    intent?.action.equals(Constants.ACTION_IDATA) -> {
                        result = intent?.getStringExtra("value")
                    }
                    intent?.action.equals(Constants.ACTION_SUNMI) -> {
                        result = intent?.getStringExtra("data")
                    }
                    intent?.action.equals(Constants.ACTION_FULIYE) -> {
                        result = intent?.getStringExtra("BARCODE")
                    }
                    intent?.action.equals(Constants.ACTION_NEW_LAND) -> {
                        result = intent?.getStringExtra("SCAN_BARCODE1")
                    }
                    intent?.action.equals(Constants.ACTION_YUNDA) -> {
                        result =
                            intent?.getStringExtra("com.android.decode.intentwedge.barcode_string")
                    }
                }
                if (!TextUtils.isEmpty(result)) {
                    var str = result?.replace("\n", "")
                    onScanReceive(str!!)
                }
            }
        }
    }

    /**
     * 返回按钮
     */
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            onBackPressed()
            return true
        }
        return super.onOptionsItemSelected(item)
    }

    /**
     * 获得扫码结果
     */
    protected open fun onScanReceive(scanStr: String) {
        Log.e("广播扫码结果：", scanStr)
    }

    /**
     * 是否要使用扫码广播
     */
    protected open fun isUseScanCode(): Boolean = false

    protected open fun isTranslucentSutatus() = false

    protected abstract fun initView()

    protected abstract fun initData()

    /**
     * 隐藏键盘
     * 弹窗弹出的时候把键盘隐藏掉
     */
    protected open fun hideInputKeyboard(v: View) {
        val imm: InputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(v.windowToken, 0)
    }

    open fun bindHeadContentScroll(
        headScrollView: HorizontalScrollView,
        contentScrollView: HorizontalScrollView
    ) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            contentScrollView.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
                headScrollView.scrollTo(scrollX, scrollY)
                true
            }
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            headScrollView.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
                contentScrollView.scrollTo(scrollX, scrollY)
                true
            }
        }
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        mLastActionTime = System.currentTimeMillis()
        return super.dispatchTouchEvent(ev)
    }

    /**
     * 点击空白位置，隐藏软键盘
     */
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        if (null != this.currentFocus) {
            val mInputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
            return mInputMethodManager.hideSoftInputFromWindow(this.currentFocus!!.windowToken, 0)
        }
        return super.onTouchEvent(event)
    }

    protected open fun startTimer() {
        mLastActionTime = System.currentTimeMillis()
        println("启动定时服务")
        val intent = Intent()
        intent.action = "com.orchisky.ACTION_SEND_TIME"
        val sendIntent =
            PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
        val am = this.getSystemService(ALARM_SERVICE) as AlarmManager
        am.setRepeating(
            AlarmManager.RTC_WAKEUP,
            System.currentTimeMillis() + 10 * 1000,
            (10 * 1000).toLong(),
            sendIntent
        )
    }

    protected open fun stopTimer() {
        println("取消定时服务")
        val intent = Intent()
        intent.action = "com.orchisky.ACTION_SEND_TIME"
        val sendIntent =
            PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
        val am = this.getSystemService(ALARM_SERVICE) as AlarmManager
        am.cancel(sendIntent)
    }

    open fun showProMsg(message: String) {
        val dialog = ProTextDialog(message)
        dialog.showNow(supportFragmentManager, null)
    }

    open fun showToastOkMsg(message: String) {
        ToastHelper.showOk(this, message)
    }

    open fun showToastOtherMsg(message: String) {
        ToastHelper.showOther(this, message)
    }

    override fun onResume() {
        super.onResume()
        if (isUseScanCode()) {
            registerReceiver(receiver, filter)
        }

    }

    override fun onPause() {
        if (isUseScanCode()) {
            unregisterReceiver(receiver)
        }
        super.onPause()
    }

}